# app.py
from flask import Flask
from config import Config
from utils.database import db
from utils.exceptions import handle_exception
from controllers import workflow_bp, approval_bp
from models.workflow import WorkflowTemplate,WorkflowStep
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 初始化扩展
    db.init_app(app)
    
    # 注册蓝图
    app.register_blueprint(workflow_bp, url_prefix='/api/v1')
    app.register_blueprint(approval_bp, url_prefix='/api/v1')
    
    # 错误处理
    app.register_error_handler(Exception, handle_exception)
    
    return app

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        db.create_all()
        # 初始化测试数据
        if not WorkflowTemplate.query.first():
            # 创建审批模板
            # template = WorkflowTemplate(name="请假审批")
            # step1 = WorkflowStep(
            #     step_order=1,
            #     approver_ids=[1001, 1002],  # 指定具体审批人
            #     approve_mode='ANY'
            # )
            # db.session.add_all([template, step1])
            # db.session.commit()
            
            template = WorkflowTemplate(name="请假审批")
            db.session.add(template)
            db.session.commit()
            step1 = WorkflowStep(
                template_id=template.id,
                step_order=1,
                step_type='SERIAL',
                approve_mode='ANY',
                approver_ids=[1001, 1002],  # 指定具体审批人
                cc_user_ids=[2001]  # 抄送人
            )
            db.session.add(step1)
            db.session.commit()
            
            # 发起流程
            # instance = WorkflowService.start_workflow(
            #     template.id, 
            #     {"days": 3}, 
            #     2001
            # )
    app.run(debug=app.config['DEBUG'])
